/** yipaidingcan
 * - 订单&订单退款 {云对象} 订单系列云对象
 *  第三方技术支持来自uniCloud云对象教程: https://uniapp.dcloud.net.cn/uniCloud/cloud-obj
 * jsdoc语法提示教程：https://ask.dcloud.net.cn/docs/#//ask.dcloud.net.cn/article/129
 * @param tel 17664189378 冀** 
*/
	/**
	 * 生成唯一订单号方法 
	 * */
	function setOutTradeNo(letter) {
		const date = new Date(); // 当前日期
		const outTradeNo = letter + date.getFullYear() + '' + (date.getMonth() + 1) + '' + date.getDate() + '' + date
			.getHours() + '' + date.getMinutes() + '' + date.getSeconds(); // 根据当前日期生成订单号的前缀部分
		const random = Math.round(Math.random() * 100) + '' + Math.round(Math.random() * 100) + '' + Math.round(Math
		.random() * 100); // 生成随机数部分
		return outTradeNo + '' + random; // 返回完整的订单号
	}
	/**
	 * 根据用户Id 自增金额
	 * @param Id {string} 用户的_id
	 * @param money {int} 要插回的金额
	 * @returns {object} 返回值对象类型
	*/
	async function updateUsersMoney(Id,money){
		if(!Id){
			return {messsage:'参数不完整',error: '请联系管理员',code: 400}
		}
		const db = uniCloud.database();
		return db.collection('uni-id-users').where({_id: Id }).update({
			money: db.command.inc(money)
		});
	}
	/**
	 * 插入用户账单表 - (app-web 适用) - 
	 * @param {string} orderNo 订单号
	 * @returns {object} 返回值对象类型 code：200为正确调用
	 */
	async function insertUserBill(orderNo) {
		// 参数校验
		if (!orderNo) {
			return { messsage:'参数不完整',error: '请联系管理员',code: 400 };
		}
		const dbjql = uniCloud.databaseForJQL()
		const db = uniCloud.database()
		try {
			// 查询订单信息
			let orderFiled = "address,status,refund,create_date,rider,total_fee,provider,order_no,shop_id"
			let shopFiled = "title,logo,region,_id"
			let order = dbjql.collection("orders").where({order_no:orderNo }).field(orderFiled).getTemp({getOne:true})
			let shop = dbjql.collection("shop").field(shopFiled).getTemp({getOne:true})
			let orderRes = await dbjql.collection(order,shop).get({getOne:true,customUI:true})
			orderRes = orderRes.data
			const shopData = orderRes.shop_id[0]
			let result = {
				type:1,
				price:orderRes.total_fee,
				create_date:Date.now(),
				text:"余额支付退款",
				user:orderRes.address.user_id,
				shop:{
					_id:shopData._id,
					title:shopData._id,
					logo:shopData.logo.path
				},
				side_user:{
					_id:orderRes.address.user_id,
					nickname:orderRes.address.name,
					avatar:orderRes.address.avatar,
				},
				order_no:orderRes.order_no,
			}
			const addRes = await dbjql.collection("users_bill").add(result)
			return {
				code: 200,
				message: '成功',
				result:addRes,
			}
			
			
		} catch (error) {
			return {
				message: '内部错误',code: 500,error:'建议先联系相关管理员'+error,
			};
			dbJQL.collection('users_log').add({type: 2,text: `店铺${Data.shop_id},在‘获取可提现金额’方法时发生错误：${err}`})
		}
	}
	/**
	 * 商家端取消订单
	 * @param {string} orderNo 订单号
	 * @param {string} reason 账单原因说明
	 * @returns {object} 返回shop_bill表新增的_id
	 */
	 async function returnShopBill(orderNo, reason) {
		let dbjql = uniCloud.databaseForJQL()
		var resTotalFee = dbjql.collection("orders").where({order_no: orderNo}).field("_id,total_fee,shop_id,order_no").getTemp({getOne: true})
		let shopStore = dbjql.collection("shop").field("_id,money,title").getTemp({getOne: true})
		let result = await dbjql.collection(resTotalFee, shopStore).get({getOne: true})
		
		let deductCost = 0; // 将要扣除的20%费用
		let shopMoney = result.data.shop_id[0].money // 店铺金额
		if (result.data.total_fee < 50 && shopMoney > 0) {
			deductCost = 5;
			// 如果订单金额 < 5和店铺金额 > 0 为真
		} else if (result.data.total_fee > 5 && shopMoney > 0) {
			// 将要扣除费用 = 订单金额的20% Math.round四舍五入小数点
			deductCost = Math.round(result.data.total_fee * 0.2)
		} else {
			deductCost = 0
		}
		let Data = { // 构建shop_bill表取消订单数据
			create_date: new Date().getTime(),
			shop_id: result.data.shop_id[0]._id,
			shop: {
				_id: result.data.shop_id[0]._id,
				title: result.data.shop_id[0].title,
			},
			order: {
				order_no: setOutTradeNo("R"),
				total_fee: deductCost,
			},
			is_settlement: {
				is_true: false,
				create_time: new Date().getTime()
			},
			type: 2,
			user: {
				nickname: "易派商家",
				avatar: "https://mp-60d04191-dfc8-47dc-b1e1-36d6fc279352.cdn.bspapp.com/icons/shop_logo.png"
			},
			price: deductCost,
			text: reason
		}
		// 扣除商铺金额
		const db = uniCloud.database();
		db.collection("shop").where({_id: result.data.shop_id[0]._id}).update({money: db.command.inc(-deductCost)})
		// 添加取消订单数据
		return await dbjql.collection("shop_bill").add(Data)
	}

module.exports = {
	_before: function() { // 通用预处理器

	},
	/**
	 * 商家端取消订单方法
	 * @param {string} orderNo 订单号
	 * @param {string} reason 账单原因说明
	 * @returns {object} 返回shop_bill表新增的_id
	 */
	async onOrdersRefund(orderNo, reason) {
		var dbjql = uniCloud.databaseForJQL()
		var resTotalFee = dbjql.collection("orders").where({order_no: orderNo}).field("_id,total_fee,shop_id,order_no").getTemp({getOne: true})
		var shopStore = dbjql.collection("shop").field("_id,money,title").getTemp({getOne: true})
		var result = await dbjql.collection(resTotalFee, shopStore).get({getOne: true})
		var deductCost = 0; // 将要扣除的20%费用
		var shopMoney = result.data.shop_id[0].money // 店铺金额
		if (result.data.total_fee < 50 && shopMoney > 0) {
			deductCost = 5;
			// 如果订单金额 < 5和店铺金额 > 0 为真
		} else if (result.data.total_fee > 5 && shopMoney > 0) {
			// 将要扣除费用 = 订单金额的20% Math.round四舍五入小数点
			deductCost = Math.round(result.data.total_fee * 0.2)
		} else {
			deductCost = 0
		}
		var Data = { // 构建shop_bill表取消订单数据
			create_date: new Date().getTime(),
			shop_id: result.data.shop_id[0]._id,
			shop: {
				_id: result.data.shop_id[0]._id,
				title: result.data.shop_id[0].title,
			},
			order: {
				order_no: setOutTradeNo("R"),
				total_fee: deductCost,
			},
			is_settlement: {
				is_true: false,
				create_time: new Date().getTime()
			},
			type: 2,
			user: {
				nickname: "易派商家",
				avatar: "https://mp-60d04191-dfc8-47dc-b1e1-36d6fc279352.cdn.bspapp.com/icons/shop_logo.png"
			},
			price: deductCost,
			text: reason
		}
		// 扣除商铺金额
		const db = uniCloud.database();
		db.collection("shop").where({
			_id: result.data.shop_id[0]._id
		}).update({
			money: db.command.inc(-deductCost)
		})
		// 添加取消订单数据
		return dbjql.collection("shop_bill").add(Data)
	},
	/**
	 * 商家端取消订单
	 * @param {string} orderNo 订单号
	 * @param {string} refundDescriptioon 退款原因 
	 * @param {boolean} isPunish 商家取消惩罚-开关(如果用户申请取消订单,则关闭商家取消惩罚)
	 * @returns {object} 返回状态
	 */
	async setOrdersRefund(orderNo,refundDescriptioon=null,isPunish=true){
		// 参数校验
		if (!orderNo) return {error: '参数不完整',code: 404};
		const dbjql = uniCloud.databaseForJQL()
		const db = uniCloud.database()
		const global = uniCloud.importObject("global")
		const PUSH = uniCloud.importObject("push")
		const order = uniCloud.importObject("order")
		try {
			const resTotalFee = dbjql.collection("orders").where({order_no: orderNo}).field("_id,shop_id,order_no,status,address,user_id,refund,total_fee,provider,rider").getTemp({getOne: true})
			const shopStore = dbjql.collection("shop").field("_id,money,title,create_uid").getTemp({getOne: true})
			const ordersData = await dbjql.collection(resTotalFee, shopStore).get({getOne: true})
			if (ordersData.data.status.value >= 4) return {error:"当前订单不可退款",code:404,message:'当前订单不可退款'}
			let result = null;
			let refund = null ;
			// 改订单状态
			if(!!ordersData.data.refund) {
				refundDescriptioon = ordersData.data.refund.text
				refund = {create_time:Date.now(),text:ordersData.data.refund.text,status:1}
			}else{
				refund = null
			}
			// 将用户余额退回
			if(ordersData.data.provider.value == 'yue'){
				await updateUsersMoney(ordersData.data.user_id, ordersData.data.total_fee )
				await insertUserBill(orderNo)
			}
			// 商家账单表平台账单表,商家金额修改
			await order.orderRefund(orderNo, true, refundDescriptioon)
			await  global.updateDataToDatabase("orders", {status: {value: 9,text:refundDescriptioon,create_time: Date.now()},refund:refund}, {order_no: orderNo})
			if(refund == null && isPunish){
				result = await returnShopBill(orderNo, '订单取消处罚')
			}
			let message = {order: "订单状态改变",refund: "商家已取消订单"}
			let SHOP_USERS_ID =  ordersData.data.shop_id[0].create_uid
			// 取消订单-推送给商家自己
			PUSH.sendMessageByClientId("__UNI__1EEA680", [SHOP_USERS_ID] , message.order,message.refund, {type: 'cancelorder'})
			// // 取消订单-推送给用户
			PUSH.sendMessageByClientId("__UNI__8A62930", [ordersData.data.user_id], message.order, message.refund, {type: 'cancelorder'})
			// // 取消订单-推送给骑手 判断是否有骑手接单
			if (ordersData.data.rider) {
				PUSH.sendMessageByClientId("__UNI__89628D0", [ordersData.data.rider.user_id], message.order, message.refund, {type: 'cancelorder'})
			}
			// // 取消订单-推送给后台客服
			PUSH.sendMessageByClientId("__UNI__DC7EAB3", ['64d5f86286206658e9bb7afe'],message.order, message.refund, {type: 'cancelorder',message: 'cancelorder',order_no: this.orderNo} )
			return {
				code:200,
				error:"退款成功",
				result: result ,
			}
		} catch (error) {
			dbjql.collection('users_log').add({type: 2,text: `订单${orderNo},在‘退款时’发生内部错误：${error}`})
			return {error: '内部错误',code: 500,message: error };
		}
	}
}

